<template>
  <div>
    <a-card :bordered="false">
      <a-row>
        <a-col :sm="{ span: 12 }">
          <a-spin :spinning="confirmLoading">
            <a-form :form="form" :labelCol="{ sm: { span: 6 } }" :wrapperCol="{ sm: { span: 18 } }">
              <!-- <a-form-item  label="余额">
              <div>{{ userInfo.smsBalance }} 条</div>
            </a-form-item> -->
              <!-- <a-form-item  label="群发类型">
              <a-radio-group v-model="isDiff">
                <a-radio :value="1">相同内容</a-radio>
              </a-radio-group>
            </a-form-item> -->

              <a-form-item label="短信模版">
                <AWM-select
                  funStr="getPlatformTemplateList"
                  v-decorator="['templateId', { rules: [{ required: true, message: '短信模版不能为空' }] }]"
                  @change="handleChangeTemplate"
                  :addition="{ status: 1 }"
                  placeholder="请选择短信模版"
                ></AWM-select>
                <div class="static-num-wrap" v-if="canSend.show">条数余额: {{ canSend.number }}条</div>
              </a-form-item>
              <a-form-item label="签名">
                <a-input
                  disabled
                  v-decorator="['signature', { rules: [{ required: true, message: '签名不能为空' }] }]"
                  placeholder="请输入签名"
                ></a-input>
              </a-form-item>
              <!-- <a-form-item label="标题">
                <a-input disabled v-decorator="['subject']" placeholder="请输入短信标题"></a-input>
              </a-form-item> -->

              <a-form-item label="短信内容">
                <!-- 
              v-show="form.getFieldValue('platformTemplateId')" -->
                <a-textarea
                  v-decorator="['content', { rules: [{ required: true, message: '短信内容不能为空' }] }]"
                  @change="handleChangeContent"
                  :auto-size="{ minRows: 3, maxRows: 5 }"
                />
                <div class="static-num-wrap">说明：发送时候请将${}中的变量代码替换成实际的内容</div>
              </a-form-item>
              
              <a-form-item label="号码列表">
                <a-button icon="plus" @click="handleAdd">手动添加</a-button>

                <!-- placeholder="多个用,分割" -->
                <a-upload action="/" :customRequest="handleChangeAttr" :show-upload-list="false">
                  <a-button icon="plus">文件导入</a-button>
                </a-upload>
                (支持excel文件，最多2000个号码) &nbsp;
                <a href="/demo.xlsx" download="群发excel样例.xlsx">下载示例</a>
                <!-- @click="analysisXLSX" -->

                <div class="show-details-wrap">
                  <div class="show-details">
                    <a-row>
                      <a-col :span="10" style="margin-bottom: 20px">
                        <div>所有号码</div>
                        <div class="details-num" >{{ operatorNum.all }}</div>
                      </a-col>
                      
                      <!-- <a-col :span="4" style="margin-bottom: 20px" v-if="isInternational == 1">
                        <div>移动</div>
                        <div class="details-num">{{ operatorNum.Mobile }}</div>
                      </a-col>
                      <a-col :span="4" style="margin-bottom: 20px"  v-if="isInternational == 1">
                        <div>联通</div>
                        <div class="details-num">{{ operatorNum.Union }}</div>
                      </a-col>
                      <a-col :span="4" style="margin-bottom: 20px"  v-if="isInternational == 1">
                        <div>电信</div>
                        <div class="details-num">{{ operatorNum.Telcom }}</div>
                      </a-col> -->
                      <a-col :span="10">
                        <a-button @click="clearPhone">清空号码</a-button>
                      </a-col>
                    </a-row>
                  </div>
                </div>
              </a-form-item>
              <!-- <a-form-item
              label="屏蔽运营商"
              v-if="isInternational == 1"
            >
              <a-checkbox-group v-model="operatorType">
                <a-checkbox value="1"> 移动 </a-checkbox>
                <a-checkbox value="2"> 联通 </a-checkbox>
                <a-checkbox value="3"> 电信 </a-checkbox>
              </a-checkbox-group>
            </a-form-item> -->
              <a-form-item label="定时短信">
                <div style="display: flex; justify-content: space-between">
                  <div>
                    <a-radio-group v-model="timing">
                      <a-radio value="1" @click.native.prevent="handleClickTiming">定时</a-radio>
                    </a-radio-group>
                    <a-date-picker
                      valueFormat="YYYY-MM-DD HH:mm:ss"
                      show-time
                      placeholder="请选择时间"
                      v-decorator="['timing', { rules: [{ required: true, message: '定时不能为空' }] }]"
                      v-if="timing"
                    />
                  </div>
                  <div v-if="timing">
                    <a-button type="link" @click="handleTime(10)">10分钟后</a-button>
                    <a-button type="link" @click="handleTime(30)">30分钟后</a-button>
                    <a-button type="link" @click="handleTime(60)">1小时后</a-button>
                    <a-button type="link" @click="handleTime(1440)">24小时后</a-button>
                  </div>
                </div>
              </a-form-item>
              <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
                <a-button type="primary" @click="submit"> 提交 </a-button>
                <a-button @click="handleToList"> 记录查看 </a-button>
              </a-form-item>
            </a-form>
          </a-spin>
        </a-col>
        <a-col :sm="{ span: 12 }">
          <model-phone :sign="modelPhone.sign" :content="modelPhone.content"></model-phone>
        </a-col>
      </a-row>
    </a-card>
    <a-modal
      :title="`添加手机号码`"
      :width="640"
      :visible="addPhone.visible"
      :confirmLoading="addPhone.loading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-spin :spinning="addPhone.loading">
        <div>手机号码(多个手机号码之间以,隔开):</div>
        <br />
        <a-textarea v-model="addPhone.value" placeholder="请输入手机号码" :auto-size="{ minRows: 5, maxRows: 10 }" />
      </a-spin>
    </a-modal>
    <a-modal
      :title="`发送详情`"
      :width="640"
      :visible="showData.visible"
      @ok="
        () => {
          this.showData.visible = false
          this.showData.data = ''
        }
      "
      @cancel="
        () => {
          this.showData.visible = false
          this.showData.data = ''
        }
      "
    >
      <div>
        <a-descriptions bordered :column="2">
          <a-descriptions-item label="批次数量"> {{ showData.data.batchNum }} </a-descriptions-item>
          <a-descriptions-item label="单批次接收数"> {{ showData.data.batchSize }} </a-descriptions-item>
          <a-descriptions-item label="提交成功数"> {{ showData.data.successNum }} </a-descriptions-item>
          <a-descriptions-item label="号码总数"> {{ showData.data.totalReceive }} </a-descriptions-item>
          <a-descriptions-item label="发送时间" v-if="isTiming == 1"> {{ time }} </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import { mapGetters } from 'vuex'
import { smsSendApi } from '@/api/sms'
import XLSX from 'xlsx'
import cloneDeep from 'lodash.clonedeep'
import { uploadForQiniu } from '@/utils/qiniu'
import AWMSelect from '@/components/AWMSelect'
import ModelPhone from './mouduls/ModelPhone'
// const xlsxFile = require('@/assets/demo.xlsx')

export default {
  name: 'aaaa',
  components: {
    AWMSelect,
    ModelPhone,
  },
  data() {
    return {
      operatorType: [],
      phoneList: [],
      checkNick: false,
      form: this.$form.createForm(this),
      addPhone: {
        visible: false,
        loading: false,
        value: '',
      },
      showData: {
        visible: false,
        data: {},
      },
      fileList: [],
      loading: false,
      isDiff: 1,
      timing: null,
      time: null,
      confirmLoading: false,
      platformTemplateList: [],
      text: '',
      modelPhone: {
        sign: '',
        content: '',
      },
      canSend: {
        number: 0,
        show: false,
      },
      signatureId: null,
    }
  },
  mounted() {},
  computed: {
    ...mapGetters({ userInfo: 'userInfo', baseUrl: 'baseUrl' }), //info.smsBalance
    isTiming: function () {
      console.log(this.$route.path.indexOf('/timing'))
      return this.$route.path.indexOf('/timing') != -1
    },
    // isInternational: function () {
    //   // 2 国际  1 国内
    //   return this.$route.path.indexOf('/international/') != -1 ? 2 : 1
    // },
    operatorNum: function () {
      let operatorNum = {
          Mobile: 0,
          Union: 0,
          Telcom: 0,
          all: 0,
          list: [],
        },
        operatorType = this.operatorType
      let isChinaMobile = /^(86)?1(3[4-9]|5[012789]|8[23478]|4[478]|7[28]|9[578])\d{8}$/ //移动
      let isChinaUnion = /^(86)?1(3[0-2]|4[5]|5[56]|6[67]|7[156]|8[56]|9[6])\d{8}$/ //联通
      let isChinaTelcom = /^(86)?1(3[3])|(8[019])|(5[3])|(7[37])|(9[0139])\d{8}$/ //电信
      let { phoneList } = this

      phoneList.forEach((telphone) => {
        telphone = telphone + ''
        console.log(telphone, telphone.length)
        if (telphone.length == 11 || telphone.length == 13 || telphone.length == 14) {
          operatorNum.all++
          if (isChinaMobile.test(telphone)) {
            operatorNum.Mobile++
            if (operatorType.indexOf('1') == -1) operatorNum.list.push(telphone)
          } else if (isChinaUnion.test(telphone)) {
            operatorNum.Union++
            if (operatorType.indexOf('2') == -1) operatorNum.list.push(telphone)
          } else if (isChinaTelcom.test(telphone)) {
            operatorNum.Telcom++
            if (operatorType.indexOf('3') == -1) operatorNum.list.push(telphone)
          } else {
            operatorNum.Mobile++
            operatorNum.list.push(telphone)
          }
        }
      })
      return operatorNum
    },
  },
  watch: {
    $route: function (n) {
      console.log(n)
      this.form.resetFields()
    },
  },
  methods: {
    handleRemovePic() {
      this.fileList = []
      this.fileUrl = ''
    },
    handleChangeAttr1(a_files) {
      let self = this
      function successCB(res) {
        self.fileUrl = res.key
        self.fileList[0] = {
          uid: '1',
          name: res.key,
          status: 'done',
          url: `${baseUrl}/${res.key}`,
        }
        self.$forceUpdate()
      }
      function complateCB(res) {
        self.fileList[0].percent = res.total.percent
        self.$forceUpdate()
      }
      function errorCB(err) {
        self.fileList[0] = {
          uid: '-1',
          name: 'image.png',
          status: 'error',
        }
        self.$forceUpdate()
      }
      uploadForQiniu(a_files.file, successCB, complateCB, errorCB).then((res) => {
        this.fileList[0] = {
          uid: '1',
          name: res.key,
          status: 'uploading',
          percent: 0,
          url: `${baseUrl}/${res.key}`,
        }
        self.$forceUpdate()
      })
    },
    submit() {
      let self = this
      this.form.validateFields((errors, values) => {
        if (self.operatorNum.list.length == 0) {
          self.$message.error('可发送号码数量为空!')
          return false
        }
        this.confirmLoading = true
        if (!errors) {
          let phoneList = cloneDeep(self.operatorNum.list)

          let receive = phoneList.join(',')
          values.receive = receive
          values.signature = self.signatureId
          smsSendApi(values)
            .then((res) => {
              this.$message.success('提交成功')
              this.form.resetFields()
              this.phoneList = []
              // self.showData.visible = true
              // self.showData.data = res.data
            })
            .finally(() => {
              this.confirmLoading = false
            })
          // console.log(values)
        } else {
          this.confirmLoading = false
        }
      })
    },
    check() {},
    clearPhone() {
      this.phoneList = []
    },
    handleChangeContent(val, a) {
      this.modelPhone.content = val.target.value
    },
    handleChangeTemplate(val, a_item) {
      const { signatureName, signatureId, content } = a_item
      this.form.setFieldsValue({
        signature: signatureName || '',
        content,
      })
      this.signatureId = signatureId
      if (val) {
        this.canSend.show = true
        this.canSendNum(a_item.productId)
        this.modelPhone.sign = signatureName
        this.modelPhone.content = content
      } else {
        this.canSend.show = false
        this.modelPhone.sign = ''
        this.modelPhone.content = ''
      }
    },
    canSendNum(a_id) {
      const userInfo = this.userInfo
      const { productPrices, balance = 0 } = userInfo
      let it = productPrices.find((v) => v.productId == a_id)
      this.canSend.number = it.price ? Math.floor(balance / it.price) : '--'
    },
    handleAdd() {
      this.addPhone.visible = true
    },
    handleOk() {
      this.addPhone.loading = true
      console.log(this.addPhone.value)
      let value = this.addPhone.value.replace('/ /g', '')
      let phoneList = value.split(',')
      this.phoneList = [...this.phoneList, ...phoneList]
      setTimeout(() => {
        this.addPhone.loading = false
        this.addPhone.visible = false
        this.addPhone.value = ''
      }, 100)
    },
    handleCancel() {
      this.addPhone.visible = false
    },
    handleTime(a_time) {
      let timing = moment()
        .subtract(-1 * a_time, 'minutes')
        .format('YYYY-MM-DD HH:mm:ss')
      this.form.setFieldsValue({ timing })
    },
    handleChangeAttr(a_files) {
      let self = this
      console.log(a_files)

      var fileReader = new FileReader()
      fileReader.onload = function (ev) {
        let result = []
        try {
          var data = ev.target.result
          var workbook = XLSX.read(data, {
            type: 'binary',
          }) // 以二进制流方式读取得到整份excel表格对象
          var persons = [] // 存储获取到的数据
        } catch (e) {
          console.log('文件类型不正确')
          return
        }
        // 表格的表格范围，可用于判断表头是否数量是否正确
        var fromTo = ''
        // 遍历每张表读取
        for (var sheet in workbook.Sheets) {
          console.log(sheet)
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            fromTo = workbook.Sheets[sheet]['!ref']
            console.log(fromTo)
            persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]))
            // persons = self.trimSheetData(persons)
            // result.push(persons)
          }
        }
        self.analysisArray(persons)
      }
      fileReader.readAsBinaryString(a_files.file)
    },
    // analysisXLSX(a_files) {
    //   let self = this;

    // },
    analysisArray(data) {
      console.log(data)
      let phone0 = '',
        rarr = []
      for (let i in data[0]) {
        if (!phone0) phone0 = i
      }
      for (let i of data) {
        console.log(i, phone0, i[phone0])
        rarr.push(i[phone0])
      }
      rarr.unshift(phone0)
      this.phoneList = [...this.phoneList, ...rarr]
      console.log(rarr)
      // 多内容模式
      // let arr= [],
      //   rarr = [];
      // for (let i in data[0]) {
      //   arr.push(i)
      // }
      // for(let i of data){
      //   let item = []
      //   arr.forEach(v=>{
      //     console.log(i,v)
      //     item.push(i[v] || '')
      //   })
      //   rarr.push(item)
      // }
      // rarr.pop()
      // rarr.unshift(arr)
      // console.log(rarr)
    },
    handleChangeTiming() {
      console.log(1111)
    },
    handleClickTiming(val) {
      if (this.timing) {
        this.timing = null
      } else {
        this.timing = '1'
      }
    },
    handleToList() {
      let query = this.$route.query
      this.$router.push({ path: `/clound/log` })
    },
  },
}
</script>
<style scoped lang="less">
/deep/.ant-btn {
  margin-right: 5px;
}
.show-details-wrap {
  // text-align: center;
  line-height: 20px;
  padding: 15px;
  background: rgba(144, 147, 153, 0.1);
  margin-top: 12px;
  .show-details {
    margin-bottom: 15px;
    text-align: center;
    font-size: 16px;
    .details-num {
      font-weight: bold;
      margin-top: 5px;
    }
  }
}
.static-num-wrap {
  font-size: 12px;
  line-height: 18px;
}
</style>

 